#encoding=utf-8
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 16 21:08:57 2020

@author: pygis
"""

import matplotlib.pyplot as plt
# import numpy as np
import datetime

# import os


plt.rcParams['font.sans-serif'] = ['SimHei']  # 解决中文显示为方框的问题
plt.rcParams['axes.unicode_minus'] = False


# ax=plt.gca()
# [ax.spines[i].set_visible(False) for i in ["top","right"]]

# 灰度版
def getGant():
    timelist = [['2020-6-8', '2020-6-14'], ['2020-6-15', '2020-6-21'], ['2020-6-22', '2020-7-4'],
                ['2020-7-5', '2020-7-10'], ['2020-7-11', '2020-7-17']]
    states = ['环境配置', '设计阶段', '研发阶段', '测试阶段', '成果验收']
    xlabels = ['2020-6-8', '2020-6-15', '2020-6-21', '2020-7-5', '2020-7-11', '2020-7-17']
    ylabels = ['第一阶段', '第二阶段', '第三阶段', '第四阶段', '第五阶段']
    xtimes = [0]
    ystates = [0]
    location = 0
    plt.figure()
    plt.figure(num=3, figsize=(9, 2))  # figsize的设置长和宽

    for i in range(len(timelist)):
        Start = timelist[i][0]
        Finish = timelist[i][1]
        startTime = datetime.datetime.strptime(Start, "%Y-%m-%d")
        finishTime = datetime.datetime.strptime(Finish, "%Y-%m-%d")
        day = (finishTime - startTime).days
        #        plt.bar(40,10,label=xlabels[i],color='g')
        plt.axhline(y=i + 0.5, color='k', linestyle='-', alpha=0.5, linewidth=0.8)
        plt.barh(i, day, 0.5, location, alpha=(5 + i) / 10, color='g', align="center")  # y值，宽度，高度，起始x
        plt.text(location + 1, i + 0.52, states[i], size=10, alpha=1)
        #        plt.barh(y,width,1,location,facecolor='tan',edgecolor='r',alpha=0.6,tick_label=label,hatch=".")
        plt.xlabel(u"时间")
        plt.ylabel(u"软件工程阶段")
        location += day
        xtimes.append(location)
        ystates.append(i + 1)

    #    plt.legend()#若必要可显示图例
    plt.xticks(xtimes, xlabels, rotation='horizontal')
    plt.yticks(ystates, ylabels, rotation='horizontal')
    plt.title(u'甘特图')
    #    plt.grid(True)
    plt.savefig('甘特图.png', dpi=300, format='png', bbox_inches="tight")  # bbox_inches="tight"解决X轴时间连个字不被保存的问题
    plt.show()  # 若将show函数放在savefig之前，则容易造成保存的图片为空白，因为show函数数重新定义一个画板


# RGBA版
def getGant2():
    timelist = [['2020-6-8', '2020-6-14'], ['2020-6-15', '2020-6-21'], ['2020-6-22', '2020-7-4'],
                ['2020-7-5', '2020-7-10'], ['2020-7-11', '2020-7-17']]
    states = ['环境配置', '设计阶段', '研发阶段', '测试阶段', '成果验收']
    xlabels = ['2020-6-8', '2020-6-15', '2020-6-21', '2020-7-5', '2020-7-11', '2020-7-17']
    ylabels = ['第一阶段', '第二阶段', '第三阶段', '第四阶段', '第五阶段', '']
    ylabels.reverse()
    xtimes = [0]
    ystates = [0]
    location = 0
    # plt.figure()
    plt.figure(num=3, figsize=(9, 2))  # figsize的设置长和宽

    for i in range(len(timelist)):
        Start = timelist[i][0]
        Finish = timelist[i][1]
        startTime = datetime.datetime.strptime(Start, "%Y-%m-%d")
        finishTime = datetime.datetime.strptime(Finish, "%Y-%m-%d")
        day = (finishTime - startTime).days
        #        plt.bar(40,10,label=xlabels[i],color='g')
        plt.axhline(y=i + 0.5, color='k', linestyle='-', alpha=0.5, linewidth=0.8)
        plt.barh(len(timelist) - i, day, 0.95, location, alpha=0.6,
                 color=((len(timelist) - i) / len(timelist), i / len(timelist), 0, 1), align="center")  # y值，宽度，高度，起始x
        plt.text(location + 1, len(timelist) - i - 0.2, states[i], size=10, alpha=1)
        #        plt.barh(y,width,1,location,facecolor='tan',edgecolor='r',alpha=0.6,tick_label=label,hatch=".")
        plt.xlabel(u"时间")
        plt.ylabel(u"软件工程阶段")
        location += day
        xtimes.append(location)
        ystates.append(i + 1)

    #    plt.legend()#若必要可显示图例
    plt.xticks(xtimes, xlabels, rotation='horizontal')
    plt.yticks(ystates, ylabels, rotation='horizontal')
    plt.title(u'甘特图')
    #    plt.grid(True)
    plt.savefig('甘特图2.png', dpi=300, format='png', bbox_inches="tight")  # bbox_inches="tight"解决X轴时间连个字不被保存的问题
    plt.show()  # 若将show函数放在savefig之前，则容易造成保存的图片为空白，因为show函数数重新定义一个画板


if __name__ == "__main__":
    """测试代码"""
    # getGant()
    getGant2()

# import pandas as pd
# import plotly.figure_factory as ff
# import random
#
# r = lambda: random.randint(0, 255)
# print('#%02X%02X%02X' % (r(),r(),r()))
# colors = ['#%02X%02X%02X' % (r(), r(), r())]
#
# for i in range(1, 100):
#     colors.append('#%02X%02X%02X' % (r(), r(), r()))
#
# df = pd.DataFrame( data=[("task1", "2023-12-26 08:12:10.827977", "2023-12-26 08:27:10.827977", 37),
#           ("task2", "2023-12-26 01:12:10.827977", "2023-12-26 05:27:10.827977", 19),
#           ("task1", "2023-12-26 08:50:10.827977", "2023-12-26 13:27:10.827977", 40),
#           ("task1", "2023-12-26 01:12:10.827977", "2023-12-26 03:27:10.827977", 80),
#           ("task2", "2023-12-26 10:12:10.827977", "2023-12-26 20:27:10.827977", 90)],
#     columns=["Task", "Start", "Finish", "status"])
#
# fig = ff.create_gantt(df, colors=colors, show_colorbar=True, index_col='Task', group_tasks=True)
# fig.show()





# import numpy as np
# import matplotlib.pyplot as plt
# ticks = np.array(['task1', 'task2', 'task3', 'task4',
#                   'task5', 'task6', 'task7', 'task8'])
# y_data = np.arange(1, 9)
# x_data = np.array([0.5, 1.5, 1, 3, 0.5, 1, 1, 2])
# fig, ax = plt.subplots(1, 1)
# ax.barh(y_data, x_data, tick_label=ticks,
#         left=[7.5, 6, 5.5, 3, 3, 2, 1.5, 0], color='#7dbbb0')
# [ax.spines[i].set_visible(False) for i in ['top', 'right']]
# ax.set_title("task view")
# ax.set_xlabel("time")
# ax.grid(alpha=0.5, axis='x')
# plt.show()
